


const { BannerModel } = require('../db/model')
const { bannerUpload } = require('../utils/multer')


const list = async (req, res) => {

    const result = await BannerModel.find()


    const list = []
    result.forEach(item => {
        list.push({
            title: item.title,
            img_url: item.img_url,
            link: item.link,
            id: item._id,
            createTime: new Date(item.createTime).getTime()
        })
    })
    // BannerModel({
    //     title: '百度',
    //     img_url: '/public/banner/002.jpg'
    //   }).save()

    res.send({
        code: 1,
        massage: '获取轮播图列表成功',
        list
    })
}
// const list = async (req, res) => {
//     // 获取所有轮播图内容, 把内容返回给前端
//     const result = await BannerModel.find()

//     // 对数据进行一些处理
//     const list = []
//     result.forEach(item => {
//       list.push({
//         title: item.title,
//         img_url: item.img_url,
//         link: item.link,
//         id: item._id,
//         createTime: new Date(item.createTime).getTime()
//       })
//     })

//     // 把结果返回给前端
//     res.send({
//       code: 1,
//       message: '获取轮播图列表成功',
//       list
//     })
//   }

const add = async (req, res) => {
    const { title, link, img_url } = req.body
    const total = (await BannerModel.find()).length
    if (total >= 9) return res.send({ code: 0, massage: '图片数量超过最大添加数量 ，请重新操作' })

    const result = await BannerModel({ title, link, img_url }).save()
    if (result) res.send({ code: 1, massage: '图片添加成功' })
}
const remove = async (req, res) => {
    const { id } = req.params
    const total = (await BannerModel.find()).length
    if (total <= 3) return res.send({ code: 0, massage: '删除失败 数量已经最小了' })
    await BannerModel.findByIdAndDelete(id)
    res.send({ code: 1, massage: '删除成功' })
}
const info = async (req, res) => {
    const { id } = req.params
    const result = await BannerModel.findById(id)
    res.send({
        code: 1,
        massage: '获取成功',
        result,
        info: {
            id: result._id,
            img_url: result.img_url,
            title: result.title,
            link: result.link
        }
    })
}
const update = async (req, res) => {
    const { id, title, link, img_url } = req.body
    
    await BannerModel.findByIdAndUpdate(id, { title, link, img_url })
    res.send({ code: 1, massage: '修改成功' })

}
module.exports = {
    list,
    add,
    remove,
    info,
    update
}